package com.atguigu.flink.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * TODO wordcount - 有界流处理 （DataStream API）： 读文件 
 *
 * @author cjp
 * @version 1.0
 * @date 2021/8/6 11:16
 */
public class Flink02_WC_BoundedStream {
    public static void main(String[] args) throws Exception {
        // 0.获取 执行环境
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        // 1.读取数据
        DataStreamSource<String> inputDS = senv.readTextFile("F:\\atguigu\\01_course\\code\\flink210323\\input\\word.txt");
        // 2.处理数据
        // 2.1 压平：切分、转换格式(word,1)
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = inputDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                //切分
                String[] words = value.split(" ");
                //遍历：转换成元组，往下游发送
                for (String word : words) {
                    out.collect(new Tuple2<>(word, 1));
                }
            }
        });
        // 2.2 按照 word 分组
        KeyedStream<Tuple2<String, Integer>, Tuple> wordAndOneKB = wordAndOne.keyBy(0);
        // 2.4 按组聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = wordAndOneKB.sum(1);

        // 3.输出（打印）
        result.print("test");

        // 4.启动
        senv.execute();

    }
}
